<?php
namespace app\admin\controller;

use app\common\model\Menu;
use app\common\model\Roleauthorities;
use app\common\model\SysUser;
use think\Cache;
use think\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * 实时数据控制器
 * Class Realdata
 * @package app\gygt\controller
 */
class User extends Controller
{
    public function __construct() {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Method:POST,GET,OPTIONS");
        header("Access-Control-Allow-Headers:Authorization,x-csrf-token,X-Requested-With, Cache-Control, Expires, Content-Type");
    }

    /***
     * 用户登录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(){
        $uname = input('username','','trim');
        $passwd = input('password','','trim');

        //1 参数验证是否合法
        if (empty($uname)){
            json_error_msg("用户名不能为空！请检查");
        }elseif (empty($passwd)){
            json_error_msg("密码不能为空! 请检查");
        }

        $model = new SysUser();
        //2数据处理
        $passwd = md5($passwd);
        $con['username'] = $uname;
        $con['password'] = $passwd;

        $res =  $model->with(['role'])->field('user_id,username,phone,true_name,user_type,password,role_id')
                ->where($con)->find();
        if (empty($res)){
            json_error_msg("用户名或密码错误！");
        }
        $token =  ''.time();

        if (!$res['role_id']){
            json_error_msg("权限不足！");
        }

        //查找角色对应的菜单权限
        /*$user_roleauth_model = new Roleauthorities();
        $role_menu_ids = $user_roleauth_model->where(["role_id"=>$res['role_id']])->column('menu_id');
        if(empty($role_menu_ids)){
            json_error_msg("角色没有对应任何菜单!");
        }
        $con = [
            'ismenu'=>2,
            'menu_id'=>['in',$role_menu_ids],
        ];
        //查询所有的菜单
        $menu_model = new Menu();
        $menulst = $menu_model->where($con)->order('sort_number')->select();

        //加载树形菜单
        $menulst = $this->tree_menu($menulst,0);
        $res['auths'] = $menulst;;*/

        /*$out_time = strtotime('+4 hours');
        $res['token'] =  create_token($res['user_id'],$out_time);
        $res['token_out_time'] = $out_time*/

        //3 反馈结果
        $model = new SysUser();
        $model->save(array('token'=>$token),array('user_id'=>$res['user_id']));

        // $refresh_token_out_time = strtotime('+1 days');
        // $res['refresh_token'] = create_token($res['user_id'],$refresh_token_out_time);
        // $res['refresh_token_out_time'] = $refresh_token_out_time;
        // Cache::set("token_".$res['user_id'],$res['token'],$out_time);
        // Cache::set('refresh_token_'.$res['user_id'],$res['refresh_token'],$refresh_token_out_time);
        json_return_code($res);

    }

    /**
     * 刷新token
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function refreshToken()
    {
        $refresh_token = input('refresh_token');
        $token = input('token');
        $model = new SysUser();
        $driver = $model->where('token', $token)->find();
        if (empty($driver)) {
            json_return_code('参数错误',405);
        }
        if(!Cache::get('refresh_token_'.$driver['user_id']) or Cache::get('refresh_token_'.$driver['user_id']) != $refresh_token) {
            json_return_code('token已失效',402);
        }
        $out_time = strtotime('+2 hours');//新的过期时间
        $token = create_token($driver['user_id'], $out_time);//更新token
        if (false === $model->save(['token' => $token], ['user_id' => $driver['user_id']])) {
            Cache::clear($token);
            json_return_code('token已失效',402);
        }
        Cache::set("token_".$driver['user_id'], $token, 60*5);
        $info = [
            'token'=>$token,
        ];
        json_return_code('更新成功',200,$info);
    }

    /**
     * 退出
     * @return \think\response\Json
     */
    public function logout(){
        $token = input('token');
        $model = new SysUser();
        $info = $model->where('token',$token)->find();
        $model->save(['token'=>''],['token'=>$token]);
        if(isset($info['user_id'])){
            Cache::clear('token_'.$info['user_id']);
            Cache::clear('refresh_token_'.$info['user_id']);
        }
        json_success_msg('退出成功');
    }

    /***
     * 修改密码
     */
    public function update_password(){
        $org_pwd = input('oldPsw');
        $new_pwd = input('newPsw');
        $userid = input('user_id');
        if (empty($userid)){
            json_error_msg("用户id不能为空，请检查！");
        }
        if(empty($org_pwd)){
            json_error_msg("原密码不能为空，请检查！");
        }
        if(empty($new_pwd)){
            json_error_msg("新密码不能为空，请检查！");
        }


        $model = new SysUser();
        $user = $model->where(array('user_id'=>$userid))->find();

        if($user['password'] != md5($org_pwd) ){
            json_error_msg("原密码不正确，请检查！");
        }

        $res = $model->where(array('user_id'=>$userid))->update(array('password'=>md5($new_pwd)));
        json_success_msg($res);
    }

    public function getMd5Str()
    {
        $words = input('words','','trim');
        $str = md5($words);
        json_return_code($str);
    }

    /**
     * 通过用户user_id 获取菜单列表
     */
    public function user_menu(){
        $user_id = input('user_id');
        $user_model = new SysUser();
        $menu_model = new Menu();

        /******* 启申平台用户 权限管理 ******/
        //加载启申菜单
        //获取用户权限
        $userInfo =  $user_model->field('user_id,username,phone,true_name,user_type,company_id,role_id')
            ->where(['user_id'=>$user_id])->find();
        if (!$userInfo['role_id']){
            json_error_msg("权限不足！");
        }

        //查找角色对应的菜单权限
        $user_roleauth_model = new Roleauthorities();
        $role_menu_ids = $user_roleauth_model->where(["role_id"=>$userInfo['role_id']])->column('menu_id');
        if(empty($role_menu_ids)){
            json_error_msg("角色没有对应任何菜单!");
        }
        $con = [
            'ismenu'=>2,
            'menu_id'=>['in',$role_menu_ids],
        ];
        //查询所有的菜单
        $menulst = $menu_model->where($con)->order('sort_number')->select();
        //加载树形菜单
        $menulst = $this->tree_menu($menulst,0);
        json_success_msg($menulst);
     }

    /**
     * 组织菜单树形结构
     */
    private function tree_menu($menu_arr,$parent_id){
        $totall_arr = array();
        foreach ($menu_arr as $temp){
            if($parent_id == $temp['parent_id']){
                $menu_data = array();
                $menu_data["name"] = $temp['menu_name'];
                $menu_data["icon"] = $temp['menu_icon'];
                $menu_data["url"] = $temp['menu_url'];
                $menu_data["subMenus"] = $this->tree_menu($menu_arr,$temp['menu_id']);
                $totall_arr[] = $menu_data;
            }
        }
        return $totall_arr;
    }
}
